package com.ay.weixin.fdc.admin.superadmin.event;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;

import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.log.Log;
import org.lizar.log.Logger;
import org.lizar.util.MyMath;
import org.lizar.util.StringHelper;

import com.ay.weixin.fdc.admin.superadmin.db.IbatisSuperAdminDao;
import com.ay.weixin.fdc.admin.superadmin.domain.SuperAdmin;

public class SuperLogin extends Event implements Before{
	
	private Log log=Logger.newInstance(this.getClass());
	
	private IbatisSuperAdminDao adminDao;
	
	@Override
	public void init_property() throws Exception {
		
		adminDao=Container.get(IbatisSuperAdminDao.class);
	}

	@Override
	public String default_handling_path() {
		// TODO Auto-generated method stub
		return "/superadmin/login/*";
	}
	

	@Override
	public void handle(EventLoader el) throws ServletException,
			IOException {
		if(el.getSessionAttr("adm")!=null){
			
			el.response_to_root("/superadmin");
			
			
		}else{
			String name=el.getStr("name","").toLowerCase().trim();
			String password=el.getStr("password","").trim();
			String vcode=el.getStr("vcode").trim();
			
			if(StringHelper.isNull(name)){
				el.template("/WEB-INF/template/superadmin/login.vm");
				return;
			}
			
			String msg=login(name,password, vcode, el);
			
			if(StringHelper.isNotNull(msg)){
				el.setAttr("msg", msg);
				el.setAttr("name", name);
				el.template("/WEB-INF/template/superadmin/login.vm");
			}else{
				el.response_to_root("/superadmin");
			}
			
		}
	}
	

	
	
	private String login(String name,String password,String vcode,EventLoader el) throws IOException{
		
		if(!StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())){
			return el.i18("login.vcode_invalid");
		}
		
		if(name.length()>32){
			return el.i18("login.name_or_password_invalid");
		}
		if(StringHelper.isNull(password)){
			return el.i18("login.password_is_null");
		}
		if(password.length()!=32){
			return el.i18("login.name_or_password_invalid");
		}
		
		SuperAdmin adm=null;
		try {
			adm = adminDao.get(name);
		} catch (SQLException e) {
			log.error(e);
			return el.i18("login.server_error"); 
		}
		if(adm==null){
			return el.i18("login.name_or_password_invalid");
		}
		if(!StringHelper.equals(adm.getPassword(), MyMath.encryptionWithMD5(password))){
			return el.i18("login.name_or_password_invalid");
		}
		el.setSessionAttr("adm", adm);
		return null;
	}

	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		
		
	}

	

}
